/**
 * Created by rekey on 12/7/13.
 */
var fs = require('fs');
var crypto = require('./crypto.js');
var spawn = require('child_process').spawn;
var needle = require('needle');
var when = require('when');
var config = require('../config.js');

var mimeTypes = {
    'image/jpeg' : '.jpg',
    'jpeg' : '.jpg',
    'image/png' : '.png',
    'image/gif' : '.gif'
};
/*
 * 下载图片
 * example : down({url:'http://abc.com/a.jpg'});
 * */
function down(obj) {
    var deferred = when.defer();
    var url = obj.url;
    needle.get(url, function(err, resp, body) {
        var output = config.tmp + crypto.md5(url) + mimeTypes[resp.headers['content-type']];
        fs.writeFile(output, body, function(err) {
            if (err) {
                deferred.reject(err);
            } else {
                obj.path = output;
                deferred.resolve(obj);
            }
        });
    });
    return deferred.promise;
}

/*
 * 检测图片信息
 * example : identify({path:'/tmp/a.jpg'});
 * */
function identify(obj) {
    var deferred = when.defer();
    var imagePath = obj.path;
    var _str = '';
    var _identify = spawn('identify', ['-format', '%b,%w,%h,%m', imagePath]);
    _identify.stdout.on('data', function(data) {
        _str += data.toString();
    });
    _identify.on('exit', function(code) {
        if (code === null || _str == '' || _str.indexOf('no decode delegate for') > -1) {
            deferred.reject({
                'error' : 1,
                'message' : _str || 'file is not a image.'
            });
        } else {
            var arr = _str.split(',');
            obj.info = {
                size : arr[0],
                width : arr[1],
                height : arr[2],
                type : arr[3]
            };
            deferred.resolve(obj);
        }
    });
    return deferred.promise;
}

module.export = {
    down : down,
    identify : function(obj, isRemote) {
        if (isRemote) {
            return down(obj).then(identify);
        } else {
            return identify(obj);
        }
    }
};

//down({
//    url: 'http://173113.com/uploads/allimg/110418/2-11041P92640.jpg'
//}).then(identify).then(function (resp) {
//        console.log(resp);
//    });